package com.bite.system.service.SysUser.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bite.common.core.domain.R;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.core.enums.UserIdentity;
import com.bite.common.security.exception.ServiceException;
import com.bite.common.security.service.TokenService;
import com.bite.system.domain.SysUser.TbSysUser;
import com.bite.system.domain.SysUser.dto.SysUserSaveDTO;
import com.bite.system.mapper.SysUser.SysUserMapper;
import com.bite.system.service.SysUser.ISysUserService;
import com.bite.system.utils.BCryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * {@code @RefreshScope} 注解使得SpringBoot运行时动态刷新
 * @author 均先生
 */
@Service
@RefreshScope
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    // 从nacos中读取
    @Value("${jwt.secret}")
    private String secret;
    @Override
    public R<String> login(String userAccount, String password) {
        LambdaQueryWrapper<TbSysUser> queryWrapper = new LambdaQueryWrapper<>();
        TbSysUser sysUser = sysUserMapper.selectOne(queryWrapper
                .select(TbSysUser::getUserId,TbSysUser::getPassword)
                .eq(TbSysUser::getUserAccount,userAccount));
        if (sysUser == null) {
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        // 身份验证
        if (BCryptUtils.matchesPassword(password,sysUser.getPassword())) {
            return R.ok(tokenService.createToken(sysUser.getUserId(),secret, UserIdentity.ADMIN.getValue()));
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public boolean logout(String token) {
        return false;
    }

    @Override
    public int add(SysUserSaveDTO sysUserSaveDTO) {
        List<TbSysUser> sysUserList = sysUserMapper.selectList(new LambdaQueryWrapper<TbSysUser>()
                .eq(TbSysUser::getUserAccount, sysUserSaveDTO.getUserAccount()));

        // 不为空返回true
        if (CollectionUtil.isNotEmpty(sysUserList)) {
            throw new ServiceException(ResultCode.AILED_USER_EXISTS);
        }
        TbSysUser sysUser = new TbSysUser();
        sysUser.setUserAccount(sysUserSaveDTO.getUserAccount());
        sysUser.setPassword(BCryptUtils.encryptPassword(sysUserSaveDTO.getPassword()));
        return sysUserMapper.insert(sysUser);
    }
}
